#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()

{
    int fd = open("log.txt",O_CREAT|O_WRONLY|O_TRUNC,0666);
    if(fd < 0) {
        perror("open");
        return 1;
    }
    dup2(fd,1);//并不是交换，而是单纯的新fd拷贝旧fd
    write(fd,"hello Linux",11);
    printf("%d\n",fd);
    printf("hello Linux\n");
    fprintf(stdout,"Hello world\n");

    //输入重定向
    //int fd = open("log.txt",O_RDONLY);
    //if(fd < 0){
    //    perror("open:");
    //    return 1;
    //}
    //dup2(fd,0);
    //char buff[1024];
    //ssize_t l = read(0,buff,sizeof(buff)-1);
    //if(l > 0){
    //    buff[l]='\0';
    //    printf("%s\n",buff);
    //}
    //输出重定向
    //int fd = open("log.txt",O_CREAT|O_WRONLY|O_TRUNC,0666);
    //dup2(fd,1);//与close(1)后再打开文件写入相同
    //int cnt = 5;
    //const char* msg = "hello Linux\n";
    //while(cnt--){
    //    write(1,msg,strlen(msg));
    //}
    close(fd);
    return 0;
}
